<template>
  <div class="draft bg-hex-fff">
    <!-- 顶部 -->
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
      <div class="relative">
        <image class="pointer-events-none absolute left-0 right-0 top-0 z--9 w-full" :src="`${cdnUrl}/imgs/detail/bg.png${imgVersion}`"
               mode="aspectFill" />
        <div
          :style="{ paddingTop: `${searchBarTop}px` }"
          class="z-999 flex items-center pb-40rpx"
          @click.stop="goBack">
          <uni-icons type="back" size="32" />
          <text class="text-36rpx font-600">返回</text>
        </div>
      </div>
    </div>
    <div class="box-border w-100% bg-hex-ffffff p-32rpx container">
      <div class="mb-46rpx flex flex-col items-center justify-center">
        <div class="w-full text-center text-32rpx text-hex-7C8699">草稿箱({{ draftTotal }})</div>
      </div>
      <div class="flex flex-wrap justify-between">
        <div v-for="item in draftList" class="mb-34rpx w-47% overflow-hidden rounded-32rpx"
             style="box-shadow: 0rpx 8rpx 30rpx 0rpx rgb(0 0 0 / 5%)"
             @click="routerTo(item)">
          <div class="relative h-286rpx flex flex-col items-center justify-center bg-hex-F5F5F5">
            <image
              class="absolute left-50% top-50% h-286rpx w-100% rounded-16rpx"
              style="transform: translate(-50%, -50%);"
              :src="item.coverImage"
              mode="aspectFill"
            />
            <div v-if="item.articleType===2" class="absolute right-28rpx top-32rpx flex items-center justify-center">
              <image
                :src="`${cdnUrl}/imgs/square/radio.png${imgVersion}`"
                mode="widthFix"
                class="w-60rpx"
              />
            </div>
          </div>
          <div class="box-border p-24rpx">
            <div class="multiLine-hiddle mb-24rpx">{{ item.content }}</div>
            <div class="flex items-center justify-between">
              <div class="text-24rpx text-hex-7C8699">{{ formatTime(item.createdAt) }}</div>
              <div class="text-hex-D9D9D9" @click.stop="opendelpop(item.id)">
                <image
                  class="w-40rpx"
                  :src="`${cdnUrl}/svgicons/del.svg${imgVersion}`"
                  mode="widthFix"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 删除弹窗 -->
    <confirm ref="delpop" />
  </div>
</template>

<script setup lang="ts">
let searchBarTop: any = $ref('24')
onLoad(() => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
const routerTo = (item) => {
  uni.navigateTo({
    url: `/pages-square/editDraft?articleId=${item.id}&articleType=${item.articleType}`,
  })
}
onMounted(() => {
  getDraftList()
})
// 草稿箱
//草稿箱列表
let pageNo = $ref(1)
const pageSize = $ref(6)
let isLoadMore = $ref(false)
let draftList: any = $ref([])
let draftTotal = $ref(0)
const getDraftList = () => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const reqData = { method: 'get', data: { pageNo, pageSize } }
      const { data } = await Fetch('/qqyapi/auth/article/userDraftArticle', reqData)
      if (data.code === 0) {
        draftList = draftList.concat(data.result?.dataList)
        draftList.forEach((item) => {
          if (item.articleType === 1 && isJSON(item.content)) {
            let jsonContent = JSON.parse(item.content)
            item.content = jsonContent[0].content
          }
        })
        draftTotal = Number(data.result.total)
        if (draftList.length < draftTotal) {
          isLoadMore = true
          resolve(true)
        } else {
          isLoadMore = false
          resolve(false)
        }
      } else {
        reject(new Error('Failed to get draft list'))
      }
    } catch (error) {
      reject(error)
    }
  })
}
//下拉加载更多
const getMoreData = () => {
  if (isLoadMore) {
    pageNo++
    getDraftList()
  }
}
//触底加载更多数据
onReachBottom(() => {
  getMoreData()
})
// 删除弹窗
// 删除弹窗
const delpop: any = $ref('')
const opendelpop = (id) => {
  delpop.showConfirm('确定删除此草稿吗?').then((res) => {
    if (res) {
      deleteArticle(id)
    }
  })
}
//删除草稿
const deleteArticle = async (articleId) => {
  pageNo++
  getDraftList().then(async (res) => {
    const reqData = { method: 'delete' }
    const { data, status, error } = await Fetch(`/qqyapi/auth/article/deleteArticle/${articleId}`, reqData)
    if (data.code === 0) {
      const index = draftList.findIndex(item => item.id === articleId)
      draftList.splice(index, 1)
      draftTotal -= 1
      uni.showToast({
        title: '删除成功',
        duration: 1500,
      })
    }
  })
}
//格式化时间
const formatTime = (time) => {
  let timeData = time.split(' ')[0]
  return timeData.slice(5)
}
const goTo = (url) => {
  uni.navigateTo({ url })
}
</script>

<style lang="scss">
.draft{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}
</style>
